//rollup -c --environment TARGET:shared 的 `--environment TARGET:shared`
//console.log('process.env.TARGET:', process.env.TARGET); //shared
import path from 'path';
import json from '@rollup/plugin-json';
import ts from 'rollup-plugin-typescript2';
import resolveNode from '@rollup/plugin-node-resolve';
import replace from '@rollup/plugin-replace'

const masterVersion = require('./package.json').version
const packagesDir = path.resolve(__dirname, 'packages');
const packageDir = path.resolve(packagesDir, process.env.TARGET);
const resolve = (p) => path.resolve(packageDir, p);

const pkg = require(resolve('package.json'));
//console.log('pkg:',pkg)
/*
pkg: {
  name: '@vue/shared',
  version: '1.0.0',
  main: 'index.js',
  module: 'dist/shared.esm-bundler.js',
  buildOptions: { name: 'VueShared', formats: [ 'cjs', 'esm-bundler' ] },
  license: 'MIT'
}
*/
const name = path.basename(packageDir);
const outputConfig = {
  'esm-bundler': {
    file: resolve(`dist/${name}.esm-bundler.js`),
    format: 'es'
  },
  'cjs':{
    file: resolve(`dist/${name}.cjs.js`),
    format: 'cjs'
  },
  'global':{
    file: resolve(`dist/${name}.global.js`),
    format: 'iife' //立即执行函数
  }
}

const options = pkg.buildOptions; // 自己在package.json中定义的选项

export default options.formats.map(format => crateConfig(format, outputConfig[format]));

function crateConfig(format,output){
  output.name = options.name; //buildOptions.name ---> VueShared
  output.sourcemap = true;

  const isProductionBuild =
    process.env.__DEV__ === 'false' || /\.prod\.js$/.test(output.file);
  const isBundlerESMBuild = /esm-bundler/.test(format)
  const isBrowserESMBuild = /esm-browser/.test(format)
  const isNodeBuild = format === 'cjs'
  const isGlobalBuild = /global/.test(format)

  return {
    input: resolve(`src/index.ts`), //resolve()确保了路径是相对于要打包的package
    output,
    plugins: [
      json(),
      //ts要放在resolveNode前, 要先解析出来是个ts模块, 才能近一步在模块里解析第三方
      ts({
        tsconfig: path.resolve(__dirname, 'tsconfig.json') //统一使用根包下的tsconfig.json配置
      }),
      createReplacePlugin(
        isProductionBuild,
        isBundlerESMBuild
      ),
      resolveNode()
    ]
  }
}


function createReplacePlugin(
  isProduction,
  isBundlerESMBuild
){
  const replacements = {
    __VERSION__: `"${masterVersion}"`,
    __DEV__: isBundlerESMBuild
      ? // preserve to be handled by bundlers
      `(process.env.NODE_ENV !== 'production')`
      : // hard coded dev/prod builds
      !isProduction,
  }

  //如果process.env中设置了对应的环境变量的值 就用process.env里的 而不是我们这里↑设置的replacements默认值
  Object.keys(replacements).forEach(key => {
    if (key in process.env) {
      replacements[key] = process.env[key]
    }
  })

  return replace(replacements)
}
